package com.magicsoft.app.helper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.util.Log;
import android.view.View;

public class BitmapHelper {

	private final static String TAG = "BitmapHelper";
	public static Bitmap mBitmap;

	public static Bitmap getBitmapFromView(View view) {
		view.destroyDrawingCache();
		view.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
		view.setDrawingCacheEnabled(true);
		Bitmap bitmap = view.getDrawingCache(true);
		return bitmap;
	}

	/**
	 * 
	 * @param bitmap
	 * @param isRectcle
	 *            是否需要及时回收
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, boolean isRectcle) {
		if (mBitmap != null && isRectcle) {

			mBitmap.recycle();
			mBitmap = null;
		}
		mBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
				Config.ARGB_8888);
		Canvas canvas = new Canvas(mBitmap);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = 12;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return mBitmap;
	}

	// 计算图片的缩放值
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}

	// 根据路径获得图片并压缩，返回bitmap用于显示 标准宽高：480*800
	public static Bitmap getSmallBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
		Log.i("BitmapHelper", "imagewidth = " + options.outWidth
				+ " imageheight = " + options.outHeight);
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, 480, 800);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(filePath, options);
		if (bitmap == null) {
			return null;
		}
		Bitmap newbitmap = null;

		if (bitmap.getWidth() > 480 && bitmap.getHeight() > 800) {
			newbitmap = zoomImg(bitmap, 480, 800);
		} else {
			newbitmap = bitmap;
		}

		return compressImage(newbitmap);
	}

	/**
	 * 图片按比例大小压缩方法（根据路径获取图片并压缩）： 卡标准模板宽高 760*482
	 * 
	 * @param filePath
	 *            根据路径获得图片并压缩，返回bitmap用于显示
	 * @return
	 */
	public static Bitmap getCardModeBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);// 此时返回bm为空

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, 760, 480);
		Log.e("inSampleSize", "options.inSampleSize = " + options.inSampleSize);
		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(filePath, options);

		Bitmap newbitmap = null;

		if (bitmap != null) {
			if (bitmap.getWidth() > 760 && bitmap.getHeight() > 480) {
				newbitmap = zoomImg(bitmap, 760, 480);
			} else {
				newbitmap = bitmap;
			}
		}

		if (newbitmap != null) {
			return compressImage(newbitmap);
		} else {
			return newbitmap;
		}
	}

	/**
	 * 按固定宽高处理图片
	 * 
	 * @param bm
	 *            所要转换的bitmap
	 * @param newWidth新的宽
	 * @param newHeight新的高
	 * @return 指定宽高的bitmap
	 */
	public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
		// 获得图片的宽高
		int width = bm.getWidth();
		int height = bm.getHeight();
		// 计算缩放比例
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// 得到新的图片 www.2cto.com
		Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
				true);

		Log.i("newbm",
				"height = " + newbm.getHeight() + " width = "
						+ newbm.getWidth());
		return newbm; // 压缩好比例大小后再进行质量压缩
	}

	/**
	 * 质量压缩方法
	 * 
	 * @param image
	 * @return
	 */
	private static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 500) { // 循环判断如果压缩后图片是否大于500kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	/**
	 * 利用Canvas.drawBitmap 将图片旋转
	 * 
	 * @param bm
	 * @param orientationDegree
	 * @return
	 */
	public static Bitmap adjustPhotoRotation(Bitmap bm,
			final int orientationDegree) {

		Matrix m = new Matrix();

		m.setRotate(orientationDegree, (float) bm.getWidth() / 2,
				(float) bm.getHeight() / 2);
		float targetX, targetY;
		if (orientationDegree == 90) {
			targetX = bm.getHeight();
			targetY = 0;
		} else {
			targetX = bm.getHeight();
			targetY = bm.getWidth();
		}
		Log.i(TAG, "targetX = " + targetX + " targetY = " + targetY);
		final float[] values = new float[9];
		m.getValues(values);

		float x1 = values[Matrix.MTRANS_X];
		float y1 = values[Matrix.MTRANS_Y];

		m.postTranslate(targetX - x1, targetY - y1);

		Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(),
				Bitmap.Config.ARGB_8888);
		Paint paint = new Paint();
		Canvas canvas = new Canvas(bm1);
		canvas.drawBitmap(bm, m, paint);

		return bm1;
	}

	/**
	 * 将图片旋转
	 * 
	 * @param bm
	 * @param orientationDegree
	 * @return
	 */
	public static Bitmap adjustPhotoRotation2(Bitmap bitmap,
			final int orientationDegree) {

		int w = bitmap.getWidth();
		int h = bitmap.getHeight();
		// 计算缩放率，新尺寸除原尺寸
		float scaleWidth = (float) h / w;
		float scaleHeight = (float) w / h;

		Matrix m = new Matrix();

		// 缩放图片动作
		m.postScale(scaleWidth, scaleHeight);

		m.setRotate(90); // 逆时针旋转90度

		Bitmap b = Bitmap.createBitmap(bitmap, 0, 0, w, h, m, true);

		return b;
	}

	/**
	 * 获取旋转后带圆角的图片
	 * 
	 * @param bitmap
	 * @param orientationDegree
	 * @return
	 */
	public static Bitmap getRoundedCornerAndRotateBitmap(Bitmap bitmap,
			int orientationDegree) {

		if (bitmap != null) {
			// 将图片顺时针旋转
			Bitmap b = adjustPhotoRotation(bitmap, orientationDegree);

			if (b != null) {
				// 获取带圆角图片
				Bitmap roundBitmap = getRoundedCornerBitmap(b, true);

				return roundBitmap;
			}

		}

		return null;
	}
	
	/**
	 * 
	 * 将图片按照某个角度进行旋转
	 * 
	 * 
	 * 
	 * @param bm
	 * 
	 *            需要旋转的图片
	 * 
	 * @param degree
	 * 
	 *            旋转角度
	 * 
	 * @return 旋转后的图片
	 */

	public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {

		Bitmap returnBm = null;

		// 根据旋转角度，生成旋转矩阵

		Matrix matrix = new Matrix();

		matrix.postRotate(degree);

		try {

			// 将原始图片按照旋转矩阵进行旋转，并得到新的图片

			returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
					bm.getHeight(), matrix, true);

		} catch (OutOfMemoryError e) {

		}

		if (returnBm == null) {

			returnBm = bm;

		}

		if (bm != returnBm) {

			bm.recycle();

		}

		return returnBm;

	}

	/**
	 * 根据路径获取到图片的旋转值
	 * @param path
	 * @return
	 */
	public static int getBitmapDegree(String path) {

		int degree = 0;

		try {

			// 从指定路径下读取图片，并获取其EXIF信息

			ExifInterface exifInterface = new ExifInterface(path);

			// 获取图片的旋转信息

			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,

					ExifInterface.ORIENTATION_NORMAL);

			switch (orientation) {

			case ExifInterface.ORIENTATION_ROTATE_90:

				degree = 90;

				break;

			case ExifInterface.ORIENTATION_ROTATE_180:

				degree = 180;

				break;

			case ExifInterface.ORIENTATION_ROTATE_270:

				degree = 270;

				break;

			}

		} catch (IOException e) {

			e.printStackTrace();

		}

		return degree;

	}

}
